<?php
/**
 * Created by PhpStorm.
 * User: zhanghua
 * Date: 2018/9/25
 * Time: 20:50
 */

namespace app\dlc\controller;


use app\common\controller\SunBaseController;
use app\dlc\model\AdminRole;
use app\dlc\model\AdminRolePermRelation;
use app\dlc\model\AdminRoleRelation;
use app\dlc\service\AdminPermService;
use app\dlc\service\AdminRolePermRelationService;
use app\dlc\service\AdminRoleService;
use think\Db;


class RoleController extends SunBaseController
{

    public function roleList()
    {
        $list = AdminRole::paginate();

        $this->assign('list', $list);

        return $this->returnHtml();

    }


    public function roleAdd()
    {

        if($this->request->isPost()){

            $postData = $this->request->post();

            if(AdminRole::where('name', $postData['name'])->find())
            {
                return $this->returnJson(0, '该角色已经存在！');
            }

            $menuIds = $postData['menuIds'];
            unset($postData['menuIds']);
            $menuArr = explode(',', $menuIds);

            Db::startTrans();
            try {
                $adminRoleId = AdminRoleService::save($postData);
                $adminRolePermRelation = [];
                foreach ($menuArr as $v){
                    $adminRolePermRelation[] = ['role_id' => $adminRoleId, 'perm_id' => $v];
                }
                AdminRolePermRelationService::saveAll($adminRolePermRelation);
                Db::commit();
                return $this->returnJson(1, '添加成功');
            } catch (\Exception $e) {
                Db::rollback();
                return $this->returnJson(1, '添加失败');
            }
        }


        //获取所有的菜单
        $menus = AdminPermService::getAllMenu();

        //一级菜单
        $menuLevel1 = [];

        //二级菜单
        $menuLevel2 = [];

        foreach ($menus as $menu){
            if($menu['menu_pid'] == 0){
                $menuLevel1[] = $menu;
            }else{
                $menuLevel2[] = $menu;
            }
        }

        $this->assign('menuLevel1',$menuLevel1);
        $this->assign('menuLevel2',$menuLevel2);

        return $this->returnHtml();
    }

    public function roleEdit()
    {
        if($this->request->isPost()){

            $postData = $this->request->post();

            if(isset($postData['name'])) unset($postData['name']);

            $menuIds = $postData['menuIds'];
            unset($postData['menuIds']);
            $menuArr = explode(',', $menuIds);

            Db::startTrans();
            try {
                $adminRoleId = AdminRoleService::save($postData);


                //去掉重复和多余
                $existMenus = AdminRolePermRelation::where('role_id', $postData['id'])->field('perm_id')->select()->toArray();

                $existMenusIds = [];

                foreach ($existMenus as $v){
                    $existMenusIds[] = $v['perm_id'];
                }

                $delPerms = array_diff($existMenusIds, $menuArr);//去掉的菜单

                $addPerms = array_diff($menuArr , $existMenusIds); //新增的菜单

                foreach ($delPerms as $v){
                    AdminRolePermRelation::where('perm_id', $v)->where('role_id', $postData['id'])->delete();
                }

                $adminRolePermRelation = [];
                foreach ($addPerms as $v){
                    $adminRolePermRelation[] = ['role_id' => $adminRoleId, 'perm_id' => $v];
                }

                AdminRolePermRelationService::saveAll($adminRolePermRelation);

                Db::commit();
                return $this->returnJson(1, '添加成功');
            } catch (\Exception $e) {
                Db::rollback();
                return $this->returnJson(1, '添加失败');
            }
        }

        //获取所有的菜单
        $menus = AdminPermService::getAllMenu();

        //一级菜单
        $menuLevel1 = [];

        //二级菜单
        $menuLevel2 = [];

        foreach ($menus as $menu){
            if($menu['menu_pid'] == 0){
                $menuLevel1[] = $menu;
            }else{
                $menuLevel2[] = $menu;
            }
        }

        $this->assign('menuLevel1',$menuLevel1);
        $this->assign('menuLevel2',$menuLevel2);

        $roleId = max(0, intval(input('id')));

        $role = AdminRole::get($roleId);

        $roleMenu = AdminPermService::getAdminMenuByRole($roleId);

        $roleMenuIds = [];
        foreach ($roleMenu as $v){
            $roleMenuIds[] = $v['id'];
        }


        $this->assign('role', $role);
        $this->assign('roleMenuIds', $roleMenuIds);

        return $this->returnHtml();
    }


    /**
     * 删除角色
     * @return \think\Response
     */
    public function roleDel()
    {
        if($this->request->isPost()){
            $postData = $this->request->post();

            $roleId = max(0, intval(input('id')));

            if(empty($roleId)){
                return $this->returnJson(0, '缺少参数');
            }

            $menu = AdminRoleRelation::where('role_id', $roleId)->find();

            if($menu){
                return $this->returnJson(0, '角色正在被某个管理员使用中，不能直接删除！');
            }

            if(AdminRoleService::adminRoleDel($roleId)){
                return $this->returnJson(1, '菜单删除成功！');
            }else{
                return $this->returnJson(0, '菜单删除失败！');
            }
        }
    }


}